﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscreteMath
{
    public class ParseTree
    {
        public string Value { get; private set; }
        public IList<ParseTree> Successors { get; private set; }

        public ParseTree(string root)
        {
            this.Value = root;
            this.Successors = new List<ParseTree>();
        }

        public ParseTree(char root)
        {
            this.Value = root.ToString();
            this.Successors = new List<ParseTree>();
        }

        public void AddSuccessor(ParseTree tree)
        {
            this.Successors.Add(tree);
        }

        public IList<ParseTree> CalculateLeaves()
        {
            List<ParseTree> leaves = new List<ParseTree>();

            if (this.Successors.Count == 0)
            {
                leaves.Add(this);
                return leaves;
            }

            foreach (ParseTree child in this.Successors)
            {
                leaves.AddRange(child.CalculateLeaves());
            }

            return leaves;
        }

        public int CalculateHeight()
        {
            if (this.Successors.Count == 0)
                return 0;

            return 1 + this.Successors.Max(x => x.CalculateHeight());
        }

        public override string ToString()
        {
            return this.Value;
        }
    }
}
